package com.lvtongka.app.ui.recharge

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.ViewModelProvider
import com.androideasy.permissions.EasyPermissions
import com.androideasy.permissions.Permission
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lvtongka.app.R
import com.lvtongka.app.base.BaseActivity
import com.lvtongka.app.common.CommonUtils
import com.lvtongka.app.common.FileUtils
import com.lvtongka.app.common.GlideEngine
import com.lvtongka.app.databinding.ActivityRechargeDelayBinding
import com.lvtongka.app.fragment.common.DialogHelper
import com.lvtongka.app.okpermission.PermissionLauncher


/**
 * describe:
 * 延期
 * @author:ZhangWei(张伟)
 * date:2024/12/9
 * time:10:22
 */
class RechargeDelayActivity : BaseActivity<ActivityRechargeDelayBinding, RechargeViewModel>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        isBlack = false
        super.onCreate(savedInstanceState)
    }

    override fun initViewModel(): RechargeViewModel {
        return ViewModelProvider(this)[RechargeViewModel::class.java]
    }

    override fun initEvent() {
        binding.imgBack.setOnClickListener { finish() }

        binding.ivTakePhoto.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            takePhotos()
        }
        binding.tvGoDelay.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            val cardNo = binding.etCardNo.text.toString()
            val cardPwd = binding.etCardPwd.text.toString()
            if (TextUtils.isEmpty(cardNo)) {
                showToast("请输入卡号")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(cardPwd)) {
                showToast("请输入卡密")
                return@setOnClickListener
            }
            // 绑卡
            showLoading("延期中...")
            viewModel.cardDelay(cardNo, cardPwd)
        }

        viewModel.error.observe(this) {
            hideLoading()
            showToast(it)
        }
        viewModel.ocrData.observe(this) {
            hideLoading()
            binding.etCardNo.setText(it.ltk_card)
        }

        viewModel.cardDelayData.observe(this) {
            hideLoading()
            showToast("延期成功，到期时间为${it.valid}")
        }
    }

    override fun initData() {
        binding.statusBarView.layoutParams.height = CommonUtils.getStatusBarHeight()
    }

    override fun initBinding(): ActivityRechargeDelayBinding {
        return ActivityRechargeDelayBinding.inflate(layoutInflater)
    }

    private fun takePhotos() {
        val listP = listOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if (EasyPermissions.isGranted(this, listP)) {
            initPic()
//            dispatchTakePictureIntent()
        } else {
            PermissionLauncher().with(this)
                .granted {
                    //所有权限都被授予了回调此处
                    initPic()
//                    dispatchTakePictureIntent()
                }
                .denied {
                    //有权限被拒绝回调此处
                    //rejectPermissionList为被拒绝的权限列表
                    DialogHelper.showPermissionHintDialog(this@RechargeDelayActivity, "相机和存储服务未开启", "请在设置中为本应用开启相机和存储服务以正常使用功能") {
                        PermissionLauncher.openAppDetailSettings(this@RechargeDelayActivity)
                    }
                }
                .request(
                    arrayOf(Permission.CAMERA),
                    arrayOf(getString(R.string.okpermission_camera)),
                    arrayOf(getString(R.string.okpermission_camera_rationale))
                )
        }
    }

    private fun initPic() {
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    result?.let { it ->
                        val path = it[0]?.realPath
                        path?.let {
                            val str = FileUtils.compressImageAndGetBase64String(path)
                            if (TextUtils.isEmpty(str)) {
                                showToast("图片压缩失败")
                                return@let
                            }
                            showLoading("识别中...")
                            viewModel.getOcrInfo(str!!)
                        }
                    }
                }
                override fun onCancel() {}
            })
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 20 && resultCode == RESULT_OK) {
            val str = FileUtils.compressImageAndGetBase64String(filePath!!.absolutePath)
            if (TextUtils.isEmpty(str)) {
                showToast("图片压缩失败")
                return
            }
            showLoading("识别中...")
            viewModel.getOcrInfo(str!!)
        }
    }
}